package com.cevent.community.app.common.service;

import com.cevent.community.app.common.domain.Member;
import com.cevent.community.app.common.domain.MemberExample;
import com.cevent.community.app.common.dto.MemberDto;
import com.cevent.community.app.common.dto.PageDto;
import com.cevent.community.app.common.dto.SendMailDto;
import com.cevent.community.app.common.mapper.MemberMapper;
import com.cevent.community.app.common.enums.*;
import com.cevent.community.app.common.utils.DuplicateUtil;
import com.cevent.community.app.common.utils.UUID8Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author cevent
 * @description freemarker：会员管理表服务层
 */
@Service
public class MemberService {
    private static final Logger LOG=LoggerFactory.getLogger(MemberService.class);
    @Resource
    private MemberMapper memberMapper;
    //发送邮件引用
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.properties.mail.from}")
    private String from;

    //1.无分页列表查询：dto获取domain参数
    public List<MemberDto> memberDtoList(){
        MemberExample memberExample = new MemberExample();
        memberExample.setOrderByClause("uni_id asc");
        List<Member> memberList=memberMapper.selectByExample(memberExample);
        List<MemberDto> memberDtoList = new ArrayList<MemberDto>();
        for(int i=0;i<memberList.size();i++){
            Member member=memberList.get(i);
            MemberDto memberDto=new MemberDto();
            //复制拷贝(source,target)
            BeanUtils.copyProperties(member,memberDto);
            memberDtoList.add(memberDto);
        }
        return memberDtoList;
    }

    /*2.分页查询：pageDto保存数据
        list数据集合：PageDataList
        当前页码：PageCurrent
        每页行数：PageSize
        总计函数：totalSize
        前端可返回pageDto，无需返回值
     */
    public void getMemberPageDtoList(PageDto pageDto){
        //1.分页设置（前端传入当前页和每页行数params），起始页，每页行数size
        PageHelper.startPage(pageDto.getPageCurrent(),pageDto.getPageSize());
        MemberExample memberExample=new MemberExample();

        List<Member> memberList=memberMapper.selectByExample(memberExample);
        //2.将mapper查询结果复制到pageInfo
        PageInfo<Member> pageInfo=new PageInfo<>(memberList);
        //3.pageInfo计算处理处理=>后分页的总行数set到pageDto做记录
        pageDto.setTotalSize(pageInfo.getTotal());
        List<MemberDto> memberDtoList=new ArrayList<>();
        memberList.stream().forEach(member->{
            MemberDto memberDto=new MemberDto();
            BeanUtils.copyProperties(member,memberDto);
            memberDtoList.add(memberDto);
        });
        pageDto.setPageDataList(memberDtoList);

    }

    //3.新增、修改member，将传入的id转为member对象本身
    public void save(MemberDto memberDto){
        Member member= DuplicateUtil.copy(memberDto,Member.class);
        if(StringUtils.isEmpty(memberDto.getUniId())){
            this.insert(member);
        }else{
            this.update(member);
        }

    }

    //4.删除模块
    public void delete(String uniId){
        MemberExample memberExample=new MemberExample();
        memberMapper.deleteByPrimaryKey(uniId);
    }

    //5.向外暴露dto，不暴露实体类：插入数据
    private void insert(Member member){
        member.setUniId(UUID8Util.getUUID());
        try {
        Date now =new Date();
        String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
        long time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();
        int timeInt=(int)(time/1000);
        member.setCreateTime(now);
        member.setUpdateTime(now);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        memberMapper.insert(member);
    }

    //6.更新模块
    private void update(Member member){
        try {
            Date now =new Date();
            String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
            long time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();
            int timeInt=(int)(time/1000);
            member.setUpdateTime(now);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        memberMapper.updateByPrimaryKey(member);
    }

    //7.发送QQ邮件，普通文本
    public String sendSimpleMail(){
        String msg="老婆，爱你哦~ tech by cevent!";
        try {
            SimpleMailMessage message=new SimpleMailMessage();
            message.setFrom("1540001771@qq.com");
            message.setTo("1584702630@qq.com");
            message.setSubject("主题：邮件验证！");
            message.setText(msg);
            javaMailSender.send(message);
        } catch (MailException e) {
            e.printStackTrace();
            LOG.info("发送邮件失败：{}",e);
        }
        return "TEXT邮件发送成功";
    }
    //携带html
    public String sendHtmlMail(SendMailDto sendMailDto){
        //TODO 检查sql是否存在该用户，存在这里配置name、expireDate、email、重置密码的url
        MimeMessage mimeMessage=javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper;
        String content="<div style=\"border: 1px solid #dcdcdc;color: #676767;width: 600px; margin: 0 auto; padding-bottom: 50px;position: relative;\">\n" +
                "        <div style=\"height: 60px; background: #393d49; line-height: 60px; color: #58a36f; font-size: 18px;padding-left: 10px;\">一刀coder社区综合服务平台——欢迎来到官方社区</div>\n" +
                "        <div style=\"padding: 25px\">\n" +
                "          <div>您好，"+sendMailDto.getName()+"会员，重置链接有效时间30分钟，请在" + sendMailDto.getExpireDate()+
                "    之前重置您的密码：</div>\n" +
                "          <a href=\""+sendMailDto.getUrl()+"\" style=\"padding: 10px 20px; color: #fff; background: #009e94; display: inline-block;margin: 15px 0;\">立即重置密码</a>\n" +
                "          <div style=\"padding: 5px; background: #f2f2f2;\">如果该邮件不是由你本人操作，请勿进行激活！否则你的邮箱将会被他人绑定。</div>\n" +
                "        </div>\n" +
                "        <div style=\"background: #fafafa; color: #b4b4b4;text-align: center; line-height: 45px; height: 45px; position: absolute; left: 0; bottom: 0;width: 100%;\">cevent提醒：系统邮件，请勿直接回复</div>\n" +
                "    </div>";
        try {
            mimeMessageHelper=new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(sendMailDto.getTo());
            mimeMessageHelper.setText(content,true);
            mimeMessage.setSubject(sendMailDto.getSubject());
            javaMailSender.send(mimeMessage);
            LOG.info("邮件发送成功：{}",mimeMessage);
        } catch (MessagingException e) {
            LOG.error("邮件发送失败："+e);
        }
        return "HTML邮件发送成功";
    }
    //携带附件的邮件
    public String sendAttachmentsMail(){
        return "attachment附件邮件发送成功";
    }
}
